use rocket::{get, launch, routes, State,serde::json::Json};
mod db;
mod tools;
use db::{command::get_command, user::{add_user, add_users, login, User}, Database, Resp};
use tools::{get_token, make_cors, validation};
use crate::tools::authorized::Authorized;

pub struct Context {
    pub database:Database,
}

#[get("/")]
async fn index() -> &'static str {
    "Hello, Rocket!"
}

#[get("/users")]
async fn get_users(ctx: &State<Context>,_auth:Authorized) -> Json<Resp<User>>{
    //let r = User::select_by_id(&ctx.database.db,"tb_users","1").await.unwrap().expect("failed");
    //return  Json(r);
    let u :Vec<User> = ctx.database.db.
        query_decode("select * from public.tb_users", vec![]).await.unwrap();
    let resp = Resp::new(200, "success".to_string(), u);
    Json(resp)
}
#[get("/users?<id>")]
async fn get_user_by_id(ctx: &State<Context>,id:&str) -> Json<User>{
    let u = User::select_by_id(&ctx.database.db, "public.tb_users", id).await.unwrap().expect("failed");
    return Json(u);
}

#[get("/token")]
async fn get_tokens() -> Json<String> {
    let token = get_token();
    Json(token)
}

#[get("/token?<token>")]
async fn val_tokens(token:&str) -> Json<String> {
    match validation(token) {
        Ok(_num) => Json("通过".to_string()),
        Err(_) => Json("过期".to_string()),
    }
}
#[launch]
async fn rocket() -> _ {
    let context = Context{
        database:Database::new().await,
    };
    rocket::build()
        .manage(context)
        .mount("/", routes![index,get_users,get_user_by_id,
        add_user,add_users,get_command,get_tokens,val_tokens,login])
        .attach(make_cors())
}